package com.zsh.fragments;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.zsh.adapters.MainListAdapter;
import com.zsh.entities.MerchandiseItem;
import com.zsh.entities.MerchandiseList;
import com.zsh.prototype.R;
import com.zsh.task.FastJSONRequest;
import com.zsh.task.VolleyHelper;
import com.zsh.utils.Util;
import com.zsh.views.TimeLineBasisListView;
import com.zsh.views.TimeLineBasisListView.OnPositionChangedListener;
import com.zsh.views.MainListView;
import com.zsh.views.MainListView.OnLoadMoreListener;
import com.zsh.views.MainListView.OnRefreshListener;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class Main1Fragment extends Fragment{
	private static final SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss",Locale.CHINA);//�������ڸ�ʽ
	private static final String TAG = "ZSH";
	private boolean refreshFlag = true;
	private MainListView mListView;
	private MainListAdapter mAdapter;
	private View mView=null;
	private List<MerchandiseItem> mProductsItemsList = new ArrayList<MerchandiseItem>();
	private int mCount = 0;
	
	private static final int REFRESH_FLAG = 1;
	private static final int LOAD_DATA_FLAG = 0;
	
	private static final int REFRESH_DATA_FINISH = 11;
	private static final int LOAD_DATA_FINISH = 10;
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		
		@SuppressWarnings("unchecked")
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case REFRESH_DATA_FINISH:
				if(mAdapter!=null){
					mProductsItemsList.addAll(0, (ArrayList<MerchandiseItem>)msg.obj);
					mAdapter.notifyDataSetChanged();
				}
				mListView.onRefreshComplete();	//下拉刷新完成
				break;
			case LOAD_DATA_FINISH:
				if(mAdapter!=null){
					mProductsItemsList.addAll((ArrayList<MerchandiseItem>)msg.obj);
					mAdapter.notifyDataSetChanged();
				}
				mListView.onLoadMoreComplete();	//加载更多完成
				break;
			default:
				break;
			}
		};
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setRetainInstance(true);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		//保持切换前的状态
		if (null == mView) {
			mView = LayoutInflater.from(getActivity()).inflate(
					R.layout.fragment_main1, null,false);
			if ((savedInstanceState != null) && (savedInstanceState.getSerializable("refreshFlag") != null)){
				refreshFlag = savedInstanceState.getBoolean("refreshFlag");
			}
		}
		else{
			((ViewGroup)mView.getParent()).removeView(mView);
		}
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		Log.d("ZSH", "onActivityCreated");
		super.onActivityCreated(savedInstanceState);
		if (refreshFlag) {
			initData();
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean("refreshFlag", refreshFlag);
	}
	
	private void initView() {
		mAdapter = new MainListAdapter(this.getActivity().getApplicationContext(), mProductsItemsList);
		mListView = (MainListView) mView.findViewById(R.id.pulldownview);
		mListView.setAdapter(mAdapter);
		
		mListView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				Log.e(TAG, "onRefresh");
				loadData(REFRESH_FLAG);
			}
		});

		mListView.setOnLoadListener(new OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				Log.e(TAG, "onLoad");
				loadData(LOAD_DATA_FLAG);
			}
		});

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.e(TAG, "click position:" + position);
			}
		});
		
		mListView.setOnPositionChangedListener(new OnPositionChangedListener() {
			
			@Override
			public void onPositionChanged(TimeLineBasisListView listView, int position,
					View scrollBarPanel) {
				int itemPosition;
				if (position==0) {
					itemPosition = 0;
				} 
				else{
					itemPosition = position-1;
				}
				((TextView) scrollBarPanel).setText(
					Util.dateToStr(
					mProductsItemsList.get(
						itemPosition >= mProductsItemsList.size()?mProductsItemsList.size()-1:itemPosition).getStartTime()
					)
				);
			}

		});
		
	}
	
	private void loadData(final int type) {
		new Thread(){
			private ArrayList<MerchandiseItem> itemsList = new ArrayList<MerchandiseItem>();

			@Override
			public void run() {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				switch (type) {
				case REFRESH_FLAG:
					mCount = 10;
					for (int i=0;i<mCount;i++){
						itemsList.add(new MerchandiseItem
								("商品" + String.valueOf(new Random().nextInt(100)),new Date(), "/pic/1"));
					}
					mHandler.sendMessage(mHandler.obtainMessage(REFRESH_DATA_FINISH, itemsList));
					break;

				case LOAD_DATA_FLAG:					
					mCount = 20;
					for (int i=0;i<mCount;i++){
						itemsList.add(new MerchandiseItem
								("商品" + String.valueOf(new Random().nextInt(100)),new Date(), "/pic/1"));
					}
					mHandler.sendMessage(mHandler.obtainMessage(LOAD_DATA_FINISH, itemsList));
					break;
				}
			}
		}.start();
	}
	
	private void initData() {
		String url= "http://youniya.duapp.com/Merchandise/List?DName=JDKSAJLKSJDLKAJDKSJDKLSJAK&UName=gnuhpc&cellphone=13812341234&LON=108.123453434&LAT=50.2314212322&depth=0&sign=jf23bk3434jk&sortBy=Dis&Index=0&num=5";
		Log.d("ZSH", "init");
		VolleyHelper.initVolley(getActivity());
		RequestQueue queue = VolleyHelper.getRequestQueue();
		FastJSONRequest<MerchandiseList> jsonRequest = new FastJSONRequest<MerchandiseList>(
				Request.Method.GET, 
				url, 
				MerchandiseList.class,
				new Response.Listener<MerchandiseList>(){

					@Override
					public void onResponse(MerchandiseList response) {
						initArrays(response);
						initView();
						refreshFlag = false;
					}
					
				},
				new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Toast.makeText(getActivity(), "网络中断？请检查网络后再试！",Toast.LENGTH_SHORT).show();
						String msg = (error.getMessage()==null)?"Json call failed!":error.getMessage();
						Log.e(TAG, msg);
					}
				}
		);
		queue.add(jsonRequest);
		
/*		mCount=20;
		for (int i=0;i<mCount;i++){
			mProductsItemsList.add(new MerchandiseItem
					("商品" + String.valueOf(new Random().nextInt(100)),new Date(), "/pic/1"));
		}*/
	}
	
	private void initArrays(MerchandiseList response) {
		mProductsItemsList.addAll(response.getData());
	}
	
}
